import {useState} from "react";

// 管理员设置单人考勤规则

interface UseSettings {
    settings: (id: string, morning_start_time: string, evening_end_time: string) => Promise<void>;
    isLoading: boolean;
    error: string | null;
}

export function useSettings(): UseSettings {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const token = localStorage.getItem('token');
    const settings = async (id: string, morning_start_time: string, evening_end_time: string): Promise<void> => {
        setIsLoading(true);
        setError(null);
        try {
            if (!token) {
                setError('未提供授权令牌');
                return;
            }
            const response = await fetch('http://localhost:6868/admin/setAttendanceRules', {
                method: 'POST',
                headers: {
                    'Authorization': token!,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({id, morning_start_time, evening_end_time}),
            });

            if (!response.ok) {
                throw new Error('设置失败');
            }
        } catch (error) {
            setError((error as Error).message);
        } finally {
            setIsLoading(false);
        }
    };
    return {settings, isLoading, error};
}
